import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    let message = '';
    if (exception['response'] && exception['response']['message']) {
      message = exception['response']['message'];
      if (Array.isArray(message)) {
        message = message[0];
      }
    } else {
      message = exception.message;
    }
    console.log('HTTP异常信息:', message, exception.stack);
    response.status(status).json({
      code: status,
      success: false,
      message,
    });
  }
}
